import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

export 'package:permission_handler/permission_handler.dart' show Permission, PermissionStatus;

enum PermissionResult {
  denied,
  granted,
  restricted,
  limited,
  permanentlyDenied,
  cancel,
}

class PermissionUtils {
  /// 权限描叙映射
  final Map<Permission, String> _permissionDescribe = <Permission, String>{
    Permission.calendar: "开启日历记录日期，用于查看日历记录日期和日历记录日期",
    Permission.camera: "使用本机相机权限",
    Permission.contacts: "想看你的联系人",
    Permission.location: "开启定位权限，用于查看筛选地区内容",
    Permission.locationAlways: "总是用你的定位权限",
    Permission.locationWhenInUse: "当正在使用的时候才允许用定位权限",
    Permission.mediaLibrary: "安卓不支持这个权限,对应ios MPMediaLibrary",
    Permission.microphone: "您可在开启麦克风权限后使用麦克风实现发送语音消息功能，方便您跟便捷地描述您遇到的问题、以及需要我们提供的服务和帮助。在此过程中我们会收集您的录音内容以识别您的具体诉求和客服需求",
    Permission.phone: "打电话权限",
    Permission.photos: "ios访问你的相册权限",
    Permission.photosAddOnly: "ios访问你的相册权限",
    Permission.reminders: "ios提醒事项权限",
    Permission.sensors: "传感器权限",
    Permission.sms: "想看你的信息",
    Permission.speech: "安卓的麦克风权限。ios的语音识别",
    Permission.storage: "存储权限",
    Permission.ignoreBatteryOptimizations: "安卓关闭省电策略",
    Permission.notification: "通知权限",
    Permission.accessMediaLocation: "安卓10的新权限,一些照片在其数据中会包含位置信息，允许用户查看拍摄照片的位置",
    Permission.activityRecognition: "安卓10的新权限,Activity后台活动限制",
    Permission.bluetooth: "蓝牙权限",
    Permission.manageExternalStorage: "安卓管理存储控件的权限",
    Permission.systemAlertWindow: "安卓全局弹出权限",
    Permission.requestInstallPackages: "安卓请求安装应用权限",
    Permission.appTrackingTransparency: "ios14请求跟踪",
    Permission.criticalAlerts: "ios当app处于静音或者开启勿扰模式后可以收到紧急的通知提醒",
    Permission.accessNotificationPolicy: "安卓设置手机为禁音",
  };

  /// 工厂模式
  factory PermissionUtils() => _getInstance();

  /// 单例
  static PermissionUtils get instance => _getInstance();
  static PermissionUtils? _instance;

  PermissionUtils._internal();

  static PermissionUtils _getInstance() => _instance ??= PermissionUtils._internal();

  /// 打开app系统设置
  Future<bool> get forwardAppSettings => openAppSettings();

  /// 统一集合request
  Future<Map<Permission, PermissionResult>?> request(BuildContext context, List<Permission> permissionList) async {
    if (permissionList.isEmpty) return null;

    final Map<Permission, PermissionResult> permissionResult = {};
    final Map<PermissionStatus, PermissionResult> _permissionResultMap = {
      PermissionStatus.restricted: PermissionResult.restricted,
      PermissionStatus.granted: PermissionResult.granted,
      PermissionStatus.limited: PermissionResult.limited,
      PermissionStatus.permanentlyDenied: PermissionResult.permanentlyDenied,
      PermissionStatus.denied: PermissionResult.denied,
    };

    var iterator = permissionList.iterator;
    await Future.doWhile(
      () async {
        if (!iterator.moveNext()) return false;
        final Permission current = iterator.current;
        final PermissionStatus permissionStatus = await current.status;
        if (permissionStatus.isGranted) {
          permissionResult[current] = _permissionResultMap[PermissionStatus.granted]!;
          return false;
        }

        /// ios严格模式,可能是家长控制
        if (permissionStatus.isRestricted) {
          permissionResult[current] = _permissionResultMap[PermissionStatus.restricted]!;
          return false;
        }

        /// 永久拒绝权限
        if (permissionStatus.isPermanentlyDenied) {
          permissionResult[current] = _permissionResultMap[PermissionStatus.permanentlyDenied]!;
          return false;
        }

        /// 限制权限
        if (permissionStatus.isLimited) {
          permissionResult[current] = _permissionResultMap[PermissionStatus.limited]!;
          return false;
        }

        // 我们还没有请求许可，或者许可以前被拒绝过，但不是永久性的。
        if (permissionStatus.isDenied) {
          final bool? result;
          if (Platform.isAndroid) {
            result = await _showPermissionDialog(context, current);
          } else {
            result = true;
          }
          if (result == true) {
            final PermissionStatus requestStatus = await current.request();
            if (requestStatus.isGranted) {
              permissionResult[current] = _permissionResultMap[PermissionStatus.granted]!;
            } else if (requestStatus.isLimited) {
              permissionResult[current] = _permissionResultMap[PermissionStatus.limited]!;
            } else if (requestStatus.isPermanentlyDenied) {
              permissionResult[current] = _permissionResultMap[PermissionStatus.permanentlyDenied]!;
            } else if (requestStatus.isRestricted) {
              permissionResult[current] = _permissionResultMap[PermissionStatus.restricted]!;
            } else if (requestStatus.isDenied) {
              permissionResult[current] = _permissionResultMap[PermissionStatus.denied]!;
            }
          }
          return false;
        }
        return false;
      },
    );
    return permissionResult;
  }

  /// 获取权限弹窗
  Future<bool?> _showPermissionDialog(context, Permission permission) async {
    return await showDialog<bool>(
      context: context,
      barrierColor: Color.fromRGBO(52, 52, 52, 0.6),
      barrierDismissible: false,
      builder: (BuildContext context) {
        return WillPopScope(
          onWillPop: () async => false,
          child: CupertinoAlertDialog(
            title: Text("权限申请"),
            content: Text(_permissionDescribe[permission]!),
            actions: [
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
                child: Text("拒绝"),
              ),
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: Text("允许"),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 没办法吊起系统的权限,需要用户手动开启的dialog提示
  Future<bool?> showOpenSettingsDialog(context) async {
    return await showDialog<bool>(
      context: context,
      barrierColor: Color.fromRGBO(52, 52, 52, 0.6),
      barrierDismissible: false,
      builder: (BuildContext context) {
        return WillPopScope(
          onWillPop: () async => false,
          child: CupertinoAlertDialog(
            title: Text("温馨提示"),
            content: Text("应用无法获取该权限，如您需要使用请前往应用设置中开启相应权限"),
            actions: [
              CupertinoDialogAction(
                child: Text("取消"),
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
              ),
              CupertinoDialogAction(
                child: Text("去设置"),
                onPressed: () {
                  Navigator.of(context).pop(true);
                  forwardAppSettings;
                },
              ),
            ],
          ),
        );
      },
    );
  }
}
